package com.yisu.expressway.manager.website.controller.goodsArchives;

import com.google.common.collect.Collections2;
import com.yisu.expressway.ewf.common.web.EasyUIGrid;
import com.yisu.expressway.ewf.common.web.JsonResult;
import com.yisu.expressway.ewf.entity.GoodsArchives;
import com.yisu.expressway.ewf.entity.GoodsCategory;
import com.yisu.expressway.manager.core.service.IGoodsArchivesService;
import com.yisu.expressway.manager.core.service.IGoodsCategory;
import com.yisu.expressway.manager.domain.request.GoodsArchivesRequest;
import com.yisu.expressway.manager.domain.request.GoodsCategoryRequest;
import com.yisu.expressway.manager.domain.util.CacheManager;
import com.yisu.expressway.manager.domain.vo.Cache;
import com.yisu.expressway.manager.website.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import static com.yisu.expressway.ewf.common.enums.ResponseCode.FAILURE;
import static com.yisu.expressway.ewf.common.enums.ResponseCode.SUCCESS;

/**
 * Created by xlt on 2017/4/20.
 */
@Controller
@RequestMapping(value = "/goodsCategory")
public class goodsCategoryController extends BaseController {
    @Resource
    private IGoodsCategory iGoodsCategory;
    @Resource
    private IGoodsArchivesService iGoodsArchivesService;

    @RequestMapping(value = "/index.htm")
    public String listPage(Model model) {
        logger.info("Go to goodsArchives goodsCategory index page...");
        try {
            model.addAttribute("titleName", "商品类目管理");
        } catch (Exception ex) {
            logger.error("商品类目管理加载异常：" + ex.getMessage(), ex);
        }
        return "/goodsArchives/goodsCategory/index";
    }

    /**
     * 获取商品分类树信息
     *
     * @param nodeId 上级节点ID
     * @return 状态
     */
    @RequestMapping(value = "/getGoodsCategoryTreeJson.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getGoodsCategoryTreeJson(String nodeId) {
        try {
            nodeId = java.net.URLDecoder.decode(nodeId, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String treeJson = iGoodsCategory.getGoodsCategoryTreeInfo(nodeId);
        return treeJson;

       /* Cache cache = CacheManager.getCacheInfo("GoodsCategory_GoodsCategoryTreeJson");
        String treeJson = "";
        if (cache != null) {
            treeJson = (String) cache.getValue();
        } else {
            treeJson = iGoodsCategory.getGoodsCategoryTreeInfo(nodeId);
            CacheManager.putCache("GoodsCategory_GoodsCategoryTreeJson", new Cache("GoodsCategory_GoodsCategoryTreeJson", treeJson, 5, false));
        }
        return treeJson;*/
    }

    /**
     * 添加树节点-商品类目信息
     *
     * @param goodsCategoryRequest 上级节点ID
     * @return 状态
     */
    @RequestMapping(value = "/getTreeNodeAction.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult getTreeNodeAction(GoodsCategoryRequest goodsCategoryRequest) {
        JsonResult jsonResult = new JsonResult();
        GoodsCategory goodsCategory = new GoodsCategory();
        try {
            if (StringUtils.isEmpty(goodsCategoryRequest.getId() + "")) {
                goodsCategoryRequest.setId(Long.valueOf(0));
            }
            goodsCategory = iGoodsCategory.getGoodsCategoryModelByPrimaryKey(goodsCategoryRequest.getId());
            if (goodsCategory == null) {
                goodsCategory = new GoodsCategory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonResult.setData(goodsCategory);
        return jsonResult;
    }

    /**
     * 添加树节点-商品类目信息
     *
     * @param goodsCategoryRequest 上级节点ID
     * @return 状态
     */
    @RequestMapping(value = "/addTreeNodeAction.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult addTreeNodeAction(GoodsCategoryRequest goodsCategoryRequest) {
        JsonResult jsonResult = new JsonResult();
        GoodsCategory goodsCategory = new GoodsCategory();
        try {
            if (StringUtils.isEmpty(goodsCategoryRequest.getId() + "")) {
                goodsCategoryRequest.setId(Long.valueOf(0));
            }
            goodsCategory = new GoodsCategory();
            SimpleDateFormat sformat = new SimpleDateFormat("yyyyMMddHHmmss");
            goodsCategory.setCategoryCode(sformat.format(new Date()));
            Integer maxSort = iGoodsCategory.getMaxSortByParentId(String.valueOf(goodsCategoryRequest.getId()));
            goodsCategory.setSort(maxSort + 1);
            goodsCategory.setId(Long.valueOf(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonResult.setData(goodsCategory);
        return jsonResult;
    }


    /**
     * 编辑商品类目信息
     *
     * @param goodsCategory 类目信息
     * @return 状态
     */
    @RequestMapping(value = "/modifyModelAction.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult modifyModelAction(HttpServletRequest request, GoodsCategory goodsCategory) {
        try {
            String pageType = "add";
            GoodsCategory entity = iGoodsCategory.getGoodsCategoryModelByPrimaryKey(goodsCategory.getId());
            String employeeNumber = getEmployeeNumber(request);
            goodsCategory.setNodePath(goodsCategory.getCategoryCode() + ",");
            if (entity == null) {
                if (!StringUtils.isEmpty(goodsCategory.getParentCode()) || goodsCategory.getParentCode().equals("0")) {
                    GoodsCategory parModel = iGoodsCategory.getGoodsCategoryModelByPrimaryKey(Long.parseLong(goodsCategory.getParentCode()));
                    if (parModel != null) {
                        goodsCategory.setNodePath(parModel.getNodePath() + goodsCategory.getCategoryCode() + ",");
                    }
                } else {
                    goodsCategory.setParentCode(String.valueOf(0));
                    goodsCategory.setNodePath(goodsCategory.getCategoryCode() + ",");
                    goodsCategory.setCreateBy(employeeNumber);
                }
            } else {
                pageType = "edit";
                GoodsCategory parModel = iGoodsCategory.getGoodsCategoryModelByPrimaryKey(Long.parseLong(goodsCategory.getParentCode()));
                if (parModel != null) {
                    goodsCategory.setNodePath(parModel.getNodePath() + goodsCategory.getCategoryCode() + ",");
                }
                goodsCategory.setUpdateBy(employeeNumber);
                SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                goodsCategory.setUpdateTime(Timestamp.valueOf(sformat.format(new Date())));
            }
            if (iGoodsCategory.modifyGoodsCategory(goodsCategory)) {
                return new JsonResult(SUCCESS.code, pageType);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(FAILURE.code, FAILURE.msg);
    }

    /**
     * 删除节点信息
     *
     * @param goodsCategory 类目信息
     * @return 状态
     */
    @RequestMapping(value = "/deleteModelAction.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult deleteModelAction(HttpServletRequest request, GoodsCategory goodsCategory) {
        try {
            if (iGoodsCategory.isHaveChildNode(String.valueOf(goodsCategory.getId()))) {
                return new JsonResult(FAILURE.code, "请先移除下级节点，不允许删除！");
            }
            //检测当前类目是否绑定了商品
            GoodsArchivesRequest goodsArchivesRequest = new GoodsArchivesRequest();
            goodsArchivesRequest.setCategoryCode(goodsCategory.getCategoryCode());
            EasyUIGrid<GoodsArchives> goodsArchives = iGoodsArchivesService.getGoodsArchivesByCategoryCodeByPage(goodsArchivesRequest);
            if (goodsArchives != null && goodsArchives.getRows() != null) {
                if (goodsArchives.getRows().size() > 0) {
                    return new JsonResult(FAILURE.code, "当前类目存在商品，请先移除；");
                }
            }
            if (iGoodsCategory.deleteGoodsCategory(goodsCategory.getId())) {
                return new JsonResult();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new JsonResult(FAILURE.code, "网络君泡妞去了.....");
    }


    /**
     * 上移节点
     *
     * @param goodsCategory 类目信息
     * @return 状态
     */
    @RequestMapping(value = "/moveUpAction.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult moveUpAction(HttpServletRequest request, GoodsCategory goodsCategory) {
        try {
            if (iGoodsCategory.moveUpByNodeId(String.valueOf(goodsCategory.getId()))) {
                return new JsonResult();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new JsonResult(FAILURE.code, FAILURE.msg);
    }

    /**
     * 下移节点
     *
     * @param goodsCategory 类目信息
     * @return 状态
     */
    @RequestMapping(value = "/moveDownAction.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult moveDownAction(HttpServletRequest request, GoodsCategory goodsCategory) {
        try {
            if (iGoodsCategory.moveDownNodeId(String.valueOf(goodsCategory.getId()))) {
                return new JsonResult();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new JsonResult(FAILURE.code, FAILURE.msg);
    }

}
